﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SAM.Framework.Javascript;
using Microsoft.ClearScript.JavaScript;
using Microsoft.ClearScript.V8;

namespace SAM.JavaScript.V8
{
    public class V8Execute : SAM.Framework.Javascript.IExecute, IExchange,IDisposable
    {
        protected V8ScriptEngine scriptEngine;
        public V8Execute()
        {
            this.scriptEngine = new V8ScriptEngine(); 
        }

        public void ExecuteNonResult(string jsCode)
        {
            scriptEngine.Execute(jsCode);
        }

        public ResultInfo Execute(string jsCode, IList<string> resultKeys)
        {
            this.ExecuteNonResult(jsCode);
            ResultInfo result = new ResultInfo();
            foreach(var item in resultKeys)
            {
                result.Content.Add(item, scriptEngine.Script[item]);
            }
            return result;
        }

        public ResultInfo Execute(string jsCode, string resultKey = "result")
        {
            return this.Execute(jsCode, new List<string>() { resultKey });
        }

        public virtual void Dispose()
        {
            this.scriptEngine.Dispose();
        }

        #region IExchange 实现

        public void AddHostType(Type type)
        {
            this.scriptEngine.AddHostType(type);
        }

        public void AddHostObject(string name, object hostObject)
        {
            this.scriptEngine.AddHostObject(name, hostObject);
        }

        #endregion

        ~V8Execute()
        {
            this.scriptEngine.Dispose();
        }
    }
}
